#!/bin/bash
# 获取真实用户目录
USER_HOME=$(getent passwd ${SUDO_USER:-$USER} 2>/dev/null | cut -d: -f6)
if [[ -z "$USER_HOME" ]]; then
  echo "错误：无法确定用户主目录。"
  exit 1
fi
# 颜色定义 
RED='\033[0;31m' 
GREEN='\033[0;32m' 
YELLOW='\033[33m'
BLUE='\033[0;34m' 
NC='\033[0m' # No Color 
 
# 桌面通知函数 
notify() { 
    local title="$1" 
    local message="$2" 
    local level="$3" 
    local icon="${4:-}"  # 可选参数：图标路径
     
    case "$level" in 
        "success") 
            color="$GREEN" 
            urgency="normal" 
            ;; 
        "warning") 
            color="$BLUE" 
            urgency="normal" 
            ;; 
         "wrong") 
            color="$YELLOW" 
            urgency="normal" 
            ;;              
        "error") 
            color="$RED" 
            urgency="critical" 
            ;; 
        *) 
            color="$NC" 
            urgency="normal" 
            ;; 
    esac 
 
    echo -e "${color}${message}${NC}" 
    # 带图标和不带图标的两种调用方式
    if [[ -n "$icon" ]]; then
        notify-send -u "$urgency" -i "$icon" "$title" "$message" 2>/dev/null || true
    else
        notify-send -u "$urgency" "$title" "$message" 2>/dev/null || true
    fi
} 

#=====【检测软件是否有新的版本】==========
PACKAGE_NAME="wps-optimizer"
GITEE_REPO="https://gitee.com/seeker_ok/${PACKAGE_NAME}"
LOCAL_VERSION=$(dpkg-query -W --showformat='${Version}' ${PACKAGE_NAME} 2>/dev/null)
# 获取远程版本号
REMOTE_CONTROL=$(curl -sL "${GITEE_REPO}/raw/master/DEBIAN/control")
REMOTE_VERSION=$(echo "$REMOTE_CONTROL" | grep 'Version:' | awk '{print $2}')
# 版本比较函数
version_compare() {
    if [ "$1" = "$2" ]; then
        return 0
    fi
    local IFS=.
    local i ver1=($1) ver2=($2)
    for ((i=${#ver1[@]}; i<${#ver2[@]}; i++)); do
        ver1[i]=0
    done
    for ((i=0; i<${#ver1[@]}; i++)); do
        if [[ -z ${ver2[i]} ]]; then
            ver2[i]=0
        fi
        if ((10#${ver1[i]} > 10#${ver2[i]})); then
            return 1
        fi
        if ((10#${ver1[i]} < 10#${ver2[i]})); then
            return 2
        fi
    done
    return 0
}
# 主逻辑
if version_compare "$LOCAL_VERSION" "$REMOTE_VERSION"; then
  : # 本地版本与远程版本相同，不执行任何操作
elif [ $? -eq 1 ]; then
  echo -e "${wrong}本地版本 ${LOCAL_VERSION} 比远程版本 ${REMOTE_VERSION} 新${NC}"
else
  echo -e "${GREEN}发现${PACKAGE_NAME}有新版本 ${REMOTE_VERSION}，是否更新？[Yy/N]${NC}"
  read -p " " choice
  if [[ "$choice" = "y" || "$choice" = "Y" ]]; then
    DEB_URL="${GITEE_REPO}/raw/master/${PACKAGE_NAME}_${REMOTE_VERSION}_all.deb"
    x-terminal-emulator -e "bash -c \"
      echo -e '${GREEN}正在下载并安装新版本,请稍等...${NC}';
      wget -q ${DEB_URL} -O /tmp/${PACKAGE_NAME}.deb && 
      sudo apt install -y /tmp/${PACKAGE_NAME}.deb && 
      rm -rf /tmp/${PACKAGE_NAME}.deb;
      echo -e '${GREEN}软件已更新至 ${REMOTE_VERSION}，请关闭窗口重新运行${NC}';
      read -p $'${BLUE} 按任意键关闭此窗口...${NC}' \""
    exit 1
  fi
fi
#=====【检测软件是否有新的版本结束】==========

# 检测并删除旧备份
clean_old_backup() {
    local backup_dir="$1"
    if [ -d "$backup_dir" ]; then
        notify "检测到旧备份"  "备份文件路径$backup_dir"   "warning"   "/usr/share/icons/hicolor/48x48/apps/wps-optimizer.png"  
        read -p "是否删除旧备份？[Yy/N] " confirm
        if [[ $confirm =~ ^[Yy]$ ]]; then
            rm -rf "$backup_dir" && echo -e "${GREEN}已删除旧备份${NC}" || echo -e "${RED}删除失败${NC}"
        fi
    fi
}

# 备份配置文件
backup_config() {
    local config_dir="$1"
    local backup_dir="${config_dir}_bak"
    
    [ -d "$config_dir" ] && {
        clean_old_backup "${config_dir}_bak"
        mv "$config_dir" "$backup_dir"
        notify "已备份"  "$config_dir → $backup_dir"   "success"   "/usr/share/icons/hicolor/48x48/apps/wps-optimizer.png" 
    }
}

# 清理临时文件
clean_temps() {
    echo -e "${BLUE}正在清理临时文件...${NC}"
    find /tmp -maxdepth 1 $ -name "wps*" -o -name "kingsoft*" $ -exec rm -rfv {} \; 2>/dev/null
}

# 主流程
echo -e "${BLUE}🔍 正在优化WPS性能，请稍候...${NC}"
backup_config "$USER_HOME/.config/Kingsoft"
backup_config "$USER_HOME/.config/kingsoft" 
backup_config "$USER_HOME/.cache/Kingsoft"
backup_config "$USER_HOME/.cache/wps"
backup_config "$USER_HOME/.local/share/Kingsoft"
clean_temps

notify "✅ 优化完成"  "建议重启WPS以获得最佳效果"   "success"   "/usr/share/icons/hicolor/48x48/apps/wps-optimizer.png" 

echo  -e "\n${GREEN}感谢您使用本软件，软件免费使用与更新，具体软件更新请访问以下网址：https://gitee.com/seeker_ok/wps-optimizer${NC}"

read -p "$(echo -e ${BLUE}按任意键关闭此窗口...${NC})" 
